package com.bxd.baodan.update;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.widget.InsureHelperDialog;
import com.bxd.baodan.widget.InsureHelperDialog.CostumWidgetClickListener;

import org.json.JSONObject;

/**
 * 检测版本更新
 */
public class UpdateChecker {
    private static Thread mThread;
    private static Handler handler;

    public static void checkForDialog(final Activity activity, final boolean showToast) {
        handler = new Handler();
        mThread = new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                NetUtil util = new NetUtil(activity, JsonApi.CHECK_VERSION);

                try {
                    PackageInfo packageInfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);
                    String verName = packageInfo.versionName;
                    util.setParams("ver", "android-" + verName);
                    util.setParams("name", "com.bxd.baodan");// TODO: 18/2/24 要改 升级
                    String json = util.postStringResult();
                    //	String json = sendPost(activity);
                    if (json != null) {
                        parseJson(activity, json, showToast);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        mThread.start();
    }


    private static void parseJson(final Activity activity, String result, boolean showToast) {
        mThread.interrupt();
        try {
            JSONObject json = new JSONObject(result);
            if (json.getInt("code") != 0) {
                return;
            }
            JSONObject obj = new JSONObject(result).getJSONObject("data");
            //Log.i("updateInfo", obj.toString());

            final String apkUrl = obj
                    .getString(UpdateConstants.UPDATE_DOWNLOAD);
            String apkName = obj.getString(UpdateConstants.UPDATE_VERSIONNAME);
            String apkNote = obj.getString(UpdateConstants.UPDATE_NOTE);
            final int isForced = obj.optInt("isForced");
            String curName = activity.getPackageManager().getPackageInfo(
                    activity.getPackageName(), 0).versionName;

            final String updateMessage = "发现新版本,更新内容\n" + apkNote
                    + "\n是否立即更新?";
            // final String updateMessage = "发现新版本" + apkName + ",是否立即更新?";
            if (isBig(apkName, curName)) {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        /**
                         * 友盟错误日志
                         */
                        try {
                            // 进行判断是否需要进行强制更新

                            if (isForced == 1) { // 强制更新
                                showDialogForceUpdate(activity, updateMessage,
                                        apkUrl);
                            } else {
                                showDialog(activity, updateMessage, apkUrl);
                            }

                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                });
            } else {
                if (showToast) {

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(activity, "已经是最新版本啦!", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return true 为大于,false为小于
     */
    private static boolean isBig(String newName, String curName) {
        curName = curName.replace(".", "");
        newName = newName.replace(".", "");
        try {
            return Integer.valueOf(newName) > Integer.valueOf(curName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void showDialogForceUpdate(final Activity activity,
                                             String content, final String apkUrl) {
        try {
            final InsureHelperDialog dialog = new InsureHelperDialog(activity,
                    "检测到新版本", content, "现在更新", "退出");
            dialog.setCancelable(false);
            dialog.setCostumClick(new CostumWidgetClickListener() {
                @Override
                public void onSecondButtonClick() {
                    System.exit(0);
                }

                @Override
                public void onFirstButtonClick() {

                    goToDownload(activity, apkUrl);

                    if (activity != null) {
                        Toast.makeText(activity, "请到通知栏查看下载进度",
                                Toast.LENGTH_LONG).show();
                        activity.finish();
                    }

                }

                @Override
                public void onCancelButtonClick() {
                }
            });
            dialog.show();
        } catch (Exception e) {
            LogUtil.e("AlertDialog exception " + e.getMessage());
        }
    }

    /**
     * Show dialog
     *
     * @param activity
     * @see Dialog#(android.support.v4.app.FragmentActivity)
     */
    public static void showDialog(final Activity activity, String content,
                                  final String apkUrl) {

        try {
            InsureHelperDialog dialog = new InsureHelperDialog(activity,
                    "检测到新版本", content, "现在更新", "以后再说");
            dialog.setCostumClick(new CostumWidgetClickListener() {
                @Override
                public void onSecondButtonClick() {
                }

                @Override
                public void onFirstButtonClick() {
                    goToDownload(activity, apkUrl);
                }

                @Override
                public void onCancelButtonClick() {

                }
            });
            dialog.show();
        } catch (Exception e) {
            LogUtil.e("AlertDialog exception " + e.getMessage());
        }
    }


    private static void goToDownload(Activity activity, String apkUrl) {
        // Intent intent = new Intent(activity, DownloadService.class);
        Intent intent = new Intent(activity, DownloadService.class);
        String url = apkUrl.replace("https", "http");
        intent.putExtra(UpdateConstants.UPDATE_DOWNLOAD, url);

        intent.putExtra("flag_string", "DownloadService");
        activity.startService(intent);
    }

    /**
     * Check if a network available
     */
    public static boolean isNetworkAvailable(Context context) {
        boolean connected = false;
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo ni = cm.getActiveNetworkInfo();
            if (ni != null) {
                connected = ni.isConnected();
            }
        }
        return connected;
    }

    interface UpdateListener {
        boolean isNewVersion();
    }

}
